package com.fzg.service;


import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.tool.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * create by fzg
 * 2022/12/22 9:19
 */

@Slf4j
@Service
public class SearchService {


    /**
     * 通过关键字搜索获取菜谱
     * @param searchKey 搜索关键字
     * @return ResponseWrapper
     */
    public ResponseWrapper getDataBySearchKey(String searchKey){
        String headerUrl = "https://www.xiachufang.com";
        try {
            String encode = URLEncoder.encode(searchKey, "utf-8");
            String url = headerUrl + "/search/?keyword=" + encode + "&cat=1001";
            String res = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
            // String res = HttpUtils.sendGetRequest(url);
            Document document = Jsoup.parse(res);

            // 返回结果
            HashMap<String, Object> result = new HashMap<>();

            // 关键词搜索到的菜谱页面的第一个菜谱
            String foodDetailTailUrl = document.getElementsByClass("normal-recipe-list").get(0)
                    .getElementsByClass("list").get(0).getElementsByTag("a")
                    .get(0).attr("href");
            // 菜制作过程的详情页面
            String foodDetailUrl = headerUrl + foodDetailTailUrl;
            String foodDetailPage = HttpUtils.sendGetRequest(foodDetailUrl);
            Document foodDetailDocument = Jsoup.parse(foodDetailPage);

            // 菜的名字
            String foodName = foodDetailDocument.getElementsByClass("page-title").get(0).text();
            result.put("name",foodName);

            // 菜成品的图片
            String foodImage = foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                    .getElementsByTag("img").get(0).attr("src");
            result.put("image",foodImage);

            // 菜的类型
            String type = foodDetailDocument.getElementsByClass("page-container").get(0)
                    .getElementsByTag("li").get(1).getElementsByTag("a").get(0)
                    .getElementsByTag("span").get(0).text();
            result.put("type",type);

            // 菜的评分和多少人在做这道菜
            String score = foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                    .getElementsByClass("number").get(0).text();
            String peopleCount = foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                    .getElementsByClass("number").get(1).text();
            result.put("score",score);
            result.put("peopleCount",peopleCount);

            // 这道菜的材料
            ArrayList<HashMap<String, Object>> materials = new ArrayList<>();
            Elements materialElements = foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                    .getElementsByTag("table").get(0).getElementsByTag("tr");
            for (Element materialElement : materialElements) {
                HashMap<String, Object> map = new HashMap<>();
                // 材料名字
                String name = materialElement.getElementsByClass("name").get(0).text();
                map.put("name",name);
                // 材料用量
                String unit = materialElement.getElementsByClass("unit").get(0).text();
                map.put("count",unit);
                materials.add(map);
            }
            result.put("materials",materials);

            // 做这道菜的步骤
            ArrayList<HashMap<String, Object>> steps = new ArrayList<>();
            Elements stepsElements = foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                    .getElementsByClass("steps").get(0).getElementsByClass("container");
            int step = 0;
            for (Element stepsElement : stepsElements) {
                step++;
                HashMap<String, Object> map = new HashMap<>();
                map.put("step",step);
                // 步骤说明
                String stepContent = stepsElement.getElementsByTag("p").get(0).text();
                map.put("text",stepContent);
                // 步骤图
                String stepImg = stepsElement.getElementsByTag("img").get(0).attr("src");
                map.put("image",stepImg);
                steps.add(map);
            }
            result.put("steps",steps);

            // 小贴士（有的有，有的没有）
            ArrayList<String> tips = new ArrayList<>();
            if (!foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                    .getElementsByClass("tip-container").isEmpty()){
                String tipTotal = foodDetailDocument.getElementsByClass("block recipe-show").get(0)
                        .getElementsByClass("tip-container").get(0)
                        .getElementsByClass("tip").get(0).text();
                String[] tipSplit = tipTotal.split("\\d");
                tips.addAll(Arrays.asList(tipSplit));
            }
            result.put("tips", filterHandlerArrayList(tips));
            return ResponseWrapper.markSuccess(result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ResponseWrapper.markError();
        }
    }


    /**
     * 过滤处理数组
     * @param arr 参数数组
     * @return ArrayList<String>
     */
    public static ArrayList<String> filterHandlerArrayList(ArrayList<String> arr){
        ArrayList<String> res = new ArrayList<>();
        for (String s : arr) {
            if (!s.equals("")){
                if (s.indexOf("，") == 0){
                    String s1 = s.substring(1);
                    res.add(s1);
                }else if(s.indexOf(".") == 0){
                    String s1 = s.substring(1);
                    res.add(s1);
                }
            }
        }
        return res;
    }



    /**
     * 获取随机菜谱
     * @return ResponseWrapper
     */
    public ResponseWrapper getRandomRecipe(){
        // 返回结果
        ArrayList<HashMap<String, Object>> foods = new ArrayList<>();

        ArrayList<HashMap<String,Object>> typesUrlArr = new ArrayList<>();

        // 家常菜
        String familyCommonFoodsUrl = "https://www.xiachufang.com/category/40076/";
        HashMap<String, Object> familyMap = new HashMap<>();
        familyMap.put("type","家常菜");
        familyMap.put("url",familyCommonFoodsUrl);
        typesUrlArr.add(familyMap);
        // 小吃
        String snackUrl = "https://www.xiachufang.com/category/40073/";
        HashMap<String, Object> snackMap = new HashMap<>();
        snackMap.put("type","小吃");
        snackMap.put("url",snackUrl);
        typesUrlArr.add(snackMap);
        // 早餐
        String breakfastUrl = "https://www.xiachufang.com/category/40071/";
        HashMap<String, Object> breakfastMap = new HashMap<>();
        breakfastMap.put("type","早餐");
        breakfastMap.put("url",breakfastUrl);
        typesUrlArr.add(breakfastMap);
        // 甜品
        String sweetFoodUrl = "https://www.xiachufang.com/category/20135/";
        HashMap<String, Object> sweetFoodMap = new HashMap<>();
        sweetFoodMap.put("type","甜品");
        sweetFoodMap.put("url",sweetFoodUrl);
        typesUrlArr.add(sweetFoodMap);

        for (HashMap<String, Object> foodMap : typesUrlArr) {
            HashMap<String, Object> resultItemMap = new HashMap<>();
            resultItemMap.put("class",foodMap.get("type"));
            Document foodDoc = Jsoup.parse(HttpUtil.get(foodMap.get("url").toString(), StandardCharsets.UTF_8));
            // Document foodDoc = Jsoup.parse(HttpUtils.sendGetRequest(foodMap.get("url").toString()));
            ArrayList<HashMap<String, Object>> list = new ArrayList<>();
            Elements foodElements = foodDoc.getElementsByClass("normal-recipe-list").get(0)
                    .getElementsByClass("list").get(0).getElementsByTag("li");
            for (int i = 0; i < 6; i++) {
                HashMap<String, Object> foodItemMap = new HashMap<>();
                String foodImg = foodElements.get(i).child(0).getElementsByTag("a").get(0).child(0)
                        .getElementsByTag("img").attr("data-src");
                foodItemMap.put("image",foodImg);
                String name = foodElements.get(i).getElementsByTag("p").get(0).getElementsByTag("a")
                        .get(0).text();
                foodItemMap.put("name",name);
                list.add(foodItemMap);
            }
            resultItemMap.put("list",list);
            foods.add(resultItemMap);
        }
        return ResponseWrapper.markSuccess(foods);
    }


    /**
     * 随机获取5张轮播图
     * @return ResponseWrapper
     */
    public ResponseWrapper getRandomSwiper(){
        // 返回结果
        ArrayList<String> res = new ArrayList<>();

        Elements elementsByTags = Jsoup.parse(HttpUtils.sendGetRequest("https://www.xiachufang.com/"))
                .getElementsByClass("middle-panel").get(0).getElementsByTag("img");
        for (int i = 0; i < 5; i++) {
            String src = elementsByTags.get(i).attr("src");
            res.add(src);
        }

        return ResponseWrapper.markSuccess(res);
    }

}
